/**
 * Created by YanQi on 2016/9/8.
 * Copied from newRegBasic.js
 */

/**
 * ================================
 *         基础注册部分代码
 * ================================
 */
// 初始化所有请求地址
var _check_email_url = _cfg_host_passport + "/passport/ajax.php?mod=member_v2&act=check_email";
var _check_mobile_url = _cfg_host_passport + "/passport/ajax.php?mod=member_v2&act=check_mobile";
var _check_nickname_url = _cfg_host_passport + "/passport/ajax.php?mod=member_v2&act=check_nickname";
var _send_mobilecode_url = _cfg_host_passport + "/passport/ajax.php?mod=member&act=signup_mobile";
var _signup_mobile_url = _cfg_host_passport + "/passport/ajax.php?mod=member_v2&act=signup";
var _signup_email_url = _cfg_host_passport + "/passport/ajax.php?mod=member_v2&act=signup_email";
var _update_nickname_url = _cfg_host_passport + "/passport/ajax.php?mod=member_v2&act=update_nickname";

var err_flag = 0;
var tab_index = 0;
var tmr_email_cd = null;
var is_checked = 1;

var count = 120;    // 间隔函数, 1秒执行
var InterValObj;    // timer变量, 控制时间
var curCount;       // 当前剩余秒数

/* ===== 顶象相关变量 ===== */
var gt_captcha_obj;
var is_init_captcha_reg = 0;
var dx_token;
var is_pass = 1;
/* ======================= */

$(function() {
    var oTab = {
        tabs: $('.register .tit a'),
        tabInfo: $('.register .conbox'),
        activeClass: 'cur',
        eventName: 'click',
        callback_func: checkIndex
    };

    changeTab(oTab);

    // tab_index = $('.register .tit a').index($('.cur'));
    tab_index = 0;

    newLogin.init();

    dx_captcha_init();
});

var newLogin = {
    init: function () {
        //设置属性
        this.setAttribute();
        //获取坐标
        this.getElementsPosition();
        //设置容器宽高和当前屏幕显示大小一致
        this.$content.css("height", $(window).height());

        this.imgLoad(newLogin.imgRes, function () {
            $(".masking").hide();
            $(".progress_content").hide();
            newLogin.animationBeforeRegister();
        });
        newLogin.resizeImg();

        var resizeTimer = null;
        $(window).resize(function () {
            clearTimeout(resizeTimer);
            $(newLogin.$content).unbind("mousemove");

            newLogin.resizeImg();

            resizeTimer = setTimeout(function () {
                newLogin.mouseMove();
            }, 100)
        });

        this.initForm();
    },
    initForm: function () {
        //账号是否已经输入
        this.input_step1 = false;
        //密码是否已经输入
        this.input_step2 = false;
        if (tab_index == 0) {
            this.input_ctrls_name = ['username', 'mobile_code', 'm_keyword'];
            this.btn_submit = $('.btn_register.reg_mobile');
            this.btn_submit_wait = $('.register_loading.reg_mobile');
        } else if (tab_index == 1) {
            this.input_ctrls_name = ['email', 'e_keyword'];
            this.btn_submit = $('.btn_register.reg_email');
            this.btn_submit_wait = $('.register_loading.reg_email');
        } else {
            this.input_ctrls_name = [];
            console.log('Err: Invalid tab index!');
            return false;
        }

        err_flag = 0;
        hide_tip();

        $('#reg_form_' + tab_index + ' label').on('click', function (event) {
            $(this).parent().find('input[type!="hidden"]').focus();
            $(this).hide();
        });

        // 对*所有输入框*绑定获得与失去焦点的事件
        $('#reg_form_' + tab_index + ' input[type!="hidden"]').unbind('focus').bind('focus', function () {
            $(this).parent().find('label').hide();
            if (!err_flag) {
                hide_tip();
                changeSignupTipColor();
                showControlTip(this);
            }
            $(this).addClass("current");
        });

        $('#reg_form_' + tab_index + ' input[type!="hidden"]').unbind('blur').bind('blur', function () {
            if (!$.trim($(this).val())) {
                $(this).parent().find('label').show();
            } else {
                var tmp_result = checkInputValidate(this);
                // 手机号输入框单独处理逻辑
                if ($(this).attr('name') == 'username') {
                    disableGeeTest();
                    if (tmp_result) {
                        check_mobile_ajax($(this).val(), enableGeeTest);
                    }
                }
                // Email地址输入框单独处理逻辑
                if ($(this).attr('name') == 'email') {
                    if (tmp_result) {
                        check_email_ajax($(this).val());
                    }
                }
            }
            $(this).removeClass("current");
        });

        bindSubmitBtn();
        bindProcCheckBox();

        $(".username_box .n_txt").keyup(function () {
            if (!newLogin.input_step1) {
                newLogin.input_step1 = true;
                $("#bp1").css({"visibility": "visible", "opacity": "0"}).animate({opacity: 1}, 1100);
                $("#gph").css({"visibility": "visible", "opacity": "0"}).animate({opacity: 1}, 1100);
            }
        });
        $(".password_box .n_txt").keyup(function () {
            if (!newLogin.input_step2) {
                newLogin.input_step2 = true;
                $("#bp2").css({"visibility": "visible", "opacity": "0"}).animate({opacity: 1}, 1100);
                $("#gpm").css({"visibility": "visible", "opacity": "0"}).animate({opacity: 1}, 1100);
            }
        });

        $(".btn_register").hover(function () {
            $(this).css("opacity", .9)
        }, function () {
            $(this).css("opacity", 1)
        });
    },
    setAttribute: function () {
        //当前的显示比例
        this.scale = 1;
        //第一次加载
        this.isFirst = true;
        //原图宽
        this.initalWidth = 1920;
        //原图高
        this.initalHeight = 1080;
        //页面总窗口
        this.$content = $("#content");

        this.position = {};
        //标记图片资源是否加载完成
        this.isLoad = true;
        //图片资源
        this.imgRes = [
            _cfg_host_static + "/v4/www/images/signup_v2/boy_bg.jpg",
            //_cfg_host_static+"/v4/www/images/signup_v2/girl_bg.jpg",
            _cfg_host_static + "/v4/www/images/signup_v2/boy_w.png",
            //_cfg_host_static+"/v4/www/images/signup_v2/g_03.png",
            //_cfg_host_static+"/v4/www/images/signup_v2/girl_desk.png",
            _cfg_host_static + "/v4/www/images/signup_v2/yqn.png",
            //_cfg_host_static+"/v4/www/images/signup_v2/girl_people_msxm.png",
            //_cfg_host_static+"/v4/www/images/signup_v2/gril_people_huzi.png",
            _cfg_host_static + "/v4/www/images/signup_v2/boy_bg_summer.jpg",
            _cfg_host_static + "/v4/www/images/signup_v2/g_03.png",
            _cfg_host_static + "/v4/www/images/signup_v2/boy_people_yqnll.png",
            _cfg_host_static + "/v4/www/images/signup_v2/boy_people_qqxh.png",
            _cfg_host_static + "/v4/www/images/signup_v2/boy_masking_summer.jpg",
        ]
    },
    //开场动画和开场动画结束后所需要执行的代码
    animationBeforeRegister: function () {
        $(newLogin.$content).unbind("mousemove");
        $("[fadeIn]").each(function (index, element) {
            $(this).css({"visibility": "hidden"}).fadeOut(0);
        });
        $(".bg").css("margin-top", "0px");
        $(".sunshine").rotate({
            angle: 0,
            duration: 1500,
            animateTo: -40,
            callback: function () {
                newLogin.mouseMove();
            }
        });
        newLogin.mouseMove();  //如果此处为需要执行动画，则加到上面执行动画的代码的回调函数里

        $(".bg").stop(true, false).animate({"margin-top": -150 * newLogin.scale}, 1500, function () {
            newLogin.isFirst = false;
            $("[fadeIn]").each(function (index, element) {
                $(this).css({"visibility": "visible", "display": "none"}).fadeIn(400);
            });
        })
    },
    //设置鼠标移动事件
    mouseMove: function () {
        $(this.$content).bind("mousemove", function (e) {
            var cLeft = newLogin.$content.offset().left;
            var cTop = newLogin.$content.offset().top;
            var sacleHorizontal = newLogin.$content.width() / 2;
            var sacleVertical = newLogin.$content.height() / 2;
            var unitPx = 180;  //将整个宽分为100份，再乘以比例

            var disX = e.pageX - cLeft;
            var disY = e.pageY - cTop;

            $("[elementType=move]").each(function (index, element) {

                var thisId = this.id;
                var dispos = parseFloat($(this).attr("scale"));
                var currentLeft = Math.round(newLogin.position[thisId].disX * newLogin.scale - newLogin.position[thisId].width * newLogin.scale / 2);
                var currentTop = Math.round(newLogin.position[thisId].disY * newLogin.scale - newLogin.position[thisId].height * newLogin.scale / 2);
                newLogin.move($(this).get(0), {
                    "left": currentLeft + Math.round(((sacleHorizontal - disX) / unitPx) * dispos),
                    "top": currentTop + Math.round(((sacleVertical - disY) / unitPx) * dispos)
                })
            });
        })
    },
    resizeImg: function () {
        var o = this.initalWidth / this.initalHeight
        var screenWidth = $(window).width();
        var screenHeight = $(window).height();
        var a = screenWidth / screenHeight;
        if (o > a) {
            $("#content").css({"height": screenHeight, "width": screenWidth})
            $(".box,.masking").height(screenHeight).width("");
            $(".bg").height(screenHeight + 150 * newLogin.scale).width("");
            newLogin.scale = parseInt($(".bg").width()) / newLogin.initalWidth;

        } else if (o < a) {
            $("#content").css({"height": screenHeight, "width": screenWidth});
            $(".box,.bg,.masking").width(screenWidth).height("");
            newLogin.scale = screenWidth / newLogin.initalWidth;
        }
        if (!this.isFirst) {
            $(".bg").css({"margin-top": -150 * newLogin.scale});
        }

        //如果定位的图片都已经加载完成，则开放下面的功能
        if (this.isLoad) {
            //各图片在resize的时候重新定位
            $("[elementType]").each(function (index, element) {
                var thisId = this.id,
                    disX = newLogin.position[thisId].disX,
                    disY = newLogin.position[thisId].disY,
                    thisWidth = newLogin.position[thisId].width,
                    thisHeight = newLogin.position[thisId].height,
                    currentWidth = thisWidth * newLogin.scale,
                    currentHeight = thisHeight * newLogin.scale,
                    currentLeft = disX * newLogin.scale - currentWidth / 2,
                    currentTop = disY * newLogin.scale - currentHeight / 2;
                $(this).css({"left": currentLeft, "top": currentTop, "width": currentWidth, "height": currentHeight});
            });
        }
    },
    //用于判断所有图片是否加载完成,完成后执行fn
    imgLoad: function (srcJson, fn) {
        var allImagesLength = srcJson.length;
        var curLength = 0;
        for (var attr in srcJson) {
            var img = new Image();

            img.onload = function() {

                curLength++;
                var loadProgress = Math.ceil(curLength * 100 / allImagesLength);
                $(".progress_content span").text(loadProgress);

                if (curLength == allImagesLength) {
                    newLogin.isLoad = true;
                    fn();
                }
            };
            img.src = srcJson[attr];
        }
    },
    //获取绝对定位的元素，如阳光，人物等，存储到this.position里，ID为key，left和top存到的对象为value
    getElementsPosition: function () {
        $("[elementType]").each(function (index, element) {
            var thisId = this.id,
                thisLeft = parseInt($(this).css("left")),
                thisTop = parseInt($(this).css("top")),
                thisWidth = $(this).width(),
                thisHeight = $(this).height(),
                disX = thisLeft + thisWidth / 2,
                disY = thisTop + thisHeight / 2;
            newLogin.position[thisId] = {"disX": disX, "disY": disY, "width": thisWidth, "height": thisHeight}
        });
    },
    move: function (obj, json, callback) {
        var obj = $(obj).get(0);
        //先清除需要进行运动的对象已经存在的定时器。
        clearInterval(obj.timer);
        _m();
        obj.timer = setInterval(function () {
            _m();
        }, 30);
        function _m() {
            var bStop = true;
            for (var attr in json) {
                var cur = 0;
                if (attr == "opacity") {
                    //code for opacity
                    cur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
                } else {
                    cur = parseInt($(obj).css(attr));
                }
                var speed = (json[attr] - cur) / 6;
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

                if (cur != json[attr]) {
                    bStop = false;
                }
                if (attr == "opacity") {
                    try {
                        //高版本IE FF chrome等
                        obj.style.opacity = (cur + speed) / 100;
                    } catch (e) {
                        //IE6，7，8
                        obj.style.filter = "alpha(opacity=" + (cur + speed) + ")";
                    }
                } else {
                    obj.style[attr] = cur + speed + "px";
                }
            }
            if (bStop) {
                clearInterval(obj.timer);
                if (callback) {
                    callback();
                }
            }
        }
    }
};


// 顶象验证初始化
function dx_captcha_init(){
    gt_captcha_obj = null;
    gt_captcha_obj = _dx.Captcha(document.getElementById('dingxiang_captcha'), {
        appId: '7c47d2a509741c62c7b22a6e14aab676',
        style: 'popup'
    })

    gt_captcha_obj.on('verifySuccess', function (security_code) {
        dx_token = security_code;
        update_phone_show_v2();
    })

    gt_captcha_obj.on('passByServer', function (security_code) {
        dx_token = security_code;
        is_pass = 2;
    })

    gt_captcha_obj.on('verifyFail', function (msg) {
        // 会自动重置，故不做设置
    })

    gt_captcha_obj.on('loadFail', function () {
        $(".register_info").html("请刷新页面重试或者稍后再试").css("visibility","visible");
    })

    // 验证码准备就绪，可以接受用户输入时触发
    gt_captcha_obj.on('ready', function () {
    })

    gt_captcha_obj.on('hide', function () {
        // 因验证码隐藏后逻辑不一致，用dxtoken是否返回成功
        if(!dx_token){
            bindVerify();
        }
    })
}

function dx_wugan_init(){
    is_pass = 1;
    dx_token = null;
    gt_captcha_obj.reload();
}

function update_phone_show_v2() {
    var mobile_num = $('input[name="username"]').val();
    if (CheckString.isPhone(mobile_num)) {
        $("#get_verification_code").html("请稍后...").addClass("disable").unbind("click");
        var verify_data = {
            'dx_token': dx_token,
            'mobile_num': mobile_num
        };

        $.ajax({
            url: _send_mobilecode_url,
            data: verify_data,
            type: 'POST',
            dataType: 'json',
            cache: false,
            success: function(data) {
                if(is_pass == 1){
                    gt_captcha_obj.hide();
                }
                if (data.code > 0) { //获取手机验证码
                    send_mobile_message();
                } else {
                    dx_wugan_init();
                    $(".register_info").html(data.message).css("visibility","visible");
                    bindVerify();//如果验证失败，则置为初始状态，再次验证。
                }
            }
        });
    } else {
        $(".register_info").html("不存在的手机号").css("visibility","visible");
        return false;
    }
}

// 获取手机验证码
function send_mobile_message() {
    clearInterval(InterValObj);
    curCount = count;
    //开始计时
    $("#get_verification_code").html("重新发送( "+ curCount +" )");
    InterValObj = window.setInterval(set_remain_time, 1000); //启动计时器，1秒执行一次
}

// timer处理函数
function set_remain_time() {
    if (curCount == 0) {
        // 倒计时停止时，还原绑定事件
        window.clearInterval(InterValObj);
        bindVerify();//重新验证
        $("#get_verification_code").html("重新发送").removeClass("disable");
    } else {
        curCount--;
        if(curCount == 50){
            dx_wugan_init();
        }
        $("#get_verification_code").html("重新发送("+ curCount +" )").addClass("disable");
    }
}

// 注册错误信息展示
function show_error(msg) {
    err_flag = 1;
    $(".register_info").html(msg).css({"visibility":"visible","color":"#f61f1b"});
    $('.register_info').velocity({
        left:5
    },{
        duration:70,
        loop:2
    })
}

// 注册提示信息展示
function show_tip(msg) {
    $(".register_info").html(msg).css({visibility: "visible", color: '#00cb3e'});
}

// 注册提示信息隐藏
function hide_tip(){
    $(".register_info").css("visibility","hidden");
}

var regFunc = function() {
    err_flag = 0;
    // 定义需要验证的表单项
    var need_check = newLogin.input_ctrls_name;

    if (!is_checked) {
        show_error('请同意用户协议后进行注册');
        return false;
    }

    if (need_check.length && !err_flag) {
        for (key_num in need_check) {
            var ctrl_name = need_check[key_num];
            var obj = $('input[name="' + ctrl_name + '"]');
            if (!$.trim($(obj).val())) {
                err_flag = 1;
                show_error('注册信息不全');
                break;
            }
            var chk_result = checkInputValidate(obj);
            if (!chk_result) {
                err_flag = 1;
                break;
            }
        }
    }

    if (err_flag) {
        return false;
    }

    $(newLogin.btn_submit).css({"background-color":"#c7c7c7","border-bottom":"4px solid #b1b1b1"});
    $(newLogin.btn_submit).unbind("click");

    $.getScript("/passport/ajax.php?mod=member_v2&act=sigrup_token", function () {
        $(newLogin.btn_submit).hide();
        $(newLogin.btn_submit_wait).show();
        var submit_url = '';
        var submit_data = {};
        if (tab_index == 0) {
            var phone_num = $('input[name="username"]').val();
            var pass_code_m = $('input[name="m_keyword"]').val();
            var mobile_code = $('input[name="mobile_code"]').val();

            submit_url = _signup_mobile_url;
            submit_data = {
                signup_username: phone_num,
                signup_password: pass_code_m,
                mobile_code: mobile_code,
                xx_register_ver_token: window.xx_comment_token()
            }
        } else if (tab_index == 1) {
            var email_addr = $('input[name="email"]').val();
            var pass_code_e = $('input[name="e_keyword"]').val();

            submit_url = _signup_email_url;
            submit_data = {
                email_addr: email_addr,
                pass_code: pass_code_e,
                refer: referurl,
                xx_register_ver_token: window.xx_comment_token()
            }
        }
        $.post(submit_url, submit_data, function (o) {
            if (o.code > 0) {
                signupSuccessful(o);
            } else if (o.code < 0) {
                $(newLogin.btn_submit_wait).hide();
                $(newLogin.btn_submit).show();
                $(newLogin.btn_submit).css({"background-color": "#55ce7a", "border-bottom": "4px solid #299249"});
                show_error(o.message);
                bindSubmitBtn();
            }
        }, 'json');
    });
};

/**修改提示信息颜色**/
function changeSignupTipColor() {
    $(".register_info").css("color", "#00cb3e");
}

/**检测输入的手机号是否存在**/
function check_mobile_ajax(mobile, callback) {
    err_flag = 1;
    if (mobile == ''){
        return false;
    }

    $.ajax({
        url: _check_mobile_url,
        type: 'GET',
        dataType: 'json',
        data: {signup_username: mobile},
        success: function (result) {
            if (result.code > 0) {
                err_flag = 0;
                if (typeof (callback) == 'function') {
                    callback();
                }
            } else if (result.code < 0) {
                show_error(result.message);
            }
        }
    });
}

/**检测输入的邮箱是否存在**/
function check_email_ajax(email, callback) {
    err_flag = 1;
    if (email == ''){
        return false;
    }

    $.ajax({
        url: _check_email_url,
        type: 'GET',
        dataType: 'json',
        data: {email_addr: email},
        success: function (result) {
            if (result.code > 0) {
                err_flag = 0;
                if (typeof (callback) == 'function') {
                    callback();
                }
            } else if (result.code < 0) {
                show_error(result.message);
            }
        }
    });
}

function checkInputValidate(obj) {
    var ctrl_name = $(obj).attr('name');
    var val = $(obj).val();
    if (ctrl_name == 'username') {
        // 验证手机号
        if (!CheckString.isPhone(val)) {
            show_error('请输入正确的手机号');
            return false;
        }
    } else if (ctrl_name == 'email') {
        if (!CheckString.isEmail(val)) {
            show_error('Email地址格式错误');
            return false;
        }
    } else if (ctrl_name == 'mobile_code') {
        // 验证验证码
        if (!CheckString.isNumeric(val)) {
            show_error('验证码格式错误');
            return false;
        }
    } else if (ctrl_name == 'm_keyword' || ctrl_name == 'e_keyword') {
        // 验证密码
        if (val.length < 6) {
            show_error('密码至少需要6位');
            return false;
        }
        var obj_reg = new RegExp(/^[a-zA-Z0-9_]+$/);
        if (!obj_reg.test(val)) {
            show_error('密码只允许英文字母数字和下划线');
            return false;
        }
    }
    hide_tip();
    return true;
}

function changeTab(opt) {
    var tabs = opt.tabs,
        tabInfo = opt.tabInfo,
        activeClass = opt.activeClass,
        eventName = opt.eventName || "click",
        callback_func = opt.callback_func;

    tabs.bind(eventName, function() {
        var index = tabs.index(this);

        tabs.removeClass(activeClass);
        $(this).addClass(activeClass);

        tabInfo.css("display", "none");
        tabInfo.eq(index).css("display", "block");
        if (typeof (callback_func) == 'function') {
            callback_func(index);
        }
    });
}

function checkIndex(index) {
    tab_index = index;
    newLogin.initForm();
}

function bindSubmitBtn() {
    $(".btn_register").unbind('click').bind("click", function () {
        regFunc();
    });
}

function bindProcCheckBox() {
    var obj_input = $('#reg_form_' + tab_index + ' input[name="agr_protocol"]');
    is_checked = $(obj_input).is(':checked');
    $('.r_check_box .chk_proc').unbind('click').bind('click', function (e) {
        $(obj_input).trigger('click');
        is_checked = $(obj_input).is(':checked');
        if (is_checked) {
            $(this).addClass('checked');
        } else {
            $(this).removeClass('checked');
        }
    })
}

function showControlTip(obj) {
    var tip_str = $(obj).attr('data-tip');
    if (typeof (tip_str) != 'undefined' && tip_str) {
        show_tip(tip_str);
    }
}


function enableGeeTest() {
    $(".phone_verificationCode").removeClass("disable");
    $(".phone_verificationCode").attr("id", "get_verification_code");
    $("#get_verification_code").one("click", function () {
        $("#get_verification_code").html("请稍后...").addClass("disable").unbind("click");
        if(typeof(gt_captcha_obj) == "undefined" || gt_captcha_obj == "" || gt_captcha_obj == null){
            $(".register_info").html("请先完成验证").css("visibility","visible");
            return false;
        }
        if(is_pass == 2){
            update_phone_show_v2();
        }else{
            gt_captcha_obj.show();//再次开始验证
        }
    });
}
/**
 * 绑定点击事件,重置初始状态，进行再次验证
 */
function bindVerify() {
    $("#get_verification_code").html("获取手机验证码").removeClass('disable');
    $("#get_verification_code").unbind("click");
    $("#get_verification_code").one("click", function () {
        $("#get_verification_code").html("请稍后...").addClass("disable").unbind("click");
        if(typeof(gt_captcha_obj) == "undefined" || gt_captcha_obj == "" || gt_captcha_obj == null){
            $(".register_info").html("请先完成验证").css("visibility","visible");
            return false;
        }

        if(is_pass == 2){
            update_phone_show_v2();
        }else{
            gt_captcha_obj.show();//再次开始验证
        }
    });
}

function disableGeeTest() {
    $("#get_verification_code").unbind("click");
    $("#get_verification_code").html("获取手机验证码").addClass("disable");
}

function signupSuccessful(o) {
    $(".popWindow").show();
    if (tab_index == 0) {
        show_update_nickname();
    } else if (tab_index == 1) {
        if (o.jump) {
            var dialog_obj = $(".popContent3");
            $('#gochk_email1').attr({
                href: o.jump,
                target: '_blank'
            }).click(function () {
                $(dialog_obj).find('.close').trigger('click');
            })
        } else {
            var dialog_obj = $(".popContent4");
            $('#gochk_email2').click(function () {
                $(dialog_obj).find('.close').trigger('click');
            })
        }
        if (window.applicationCache) {
            showPop(dialog_obj);
        } else {
            IEshowPop(dialog_obj);
        }
        $('.mask').show();
        var cd_time = 60;
        tmr_email_cd = setInterval(function () {
            cd_time--;
            if (cd_time <= 0) {
                clearInterval(tmr_email_cd);
                $(newLogin.btn_submit_wait).hide();
                $(newLogin.btn_submit).show();
                $(newLogin.btn_submit).css({"background-color": "#55ce7a", "border-bottom": "4px solid #299249"});
                $(newLogin.btn_submit).html('再次发送验证邮件');
                bindSubmitBtn();
            } else {
                $('.register_loading').html('再次发送验证邮件(' + cd_time + ')');
            }
        }, 1000);
    }
}

function show_sdo(){
    $('#open').remove();
    var url = encodeURIComponent(_cfg_host_passport + "/open_v2/sdo.php?url=" + referurl);
    var html='';
    html += '<div id="open">';
    html += '<div class="pop_Content_II" id="window" style="height: 340px; width: 435px;  z-index: 2010;">';
    html += '<div class="pop_main" style="height: 340px; overflow: hidden;">';
    html += '<div class="pop_Header" style="z-index:100">';
    html += '<div class="pop_Content_opt">';
    html += '<a class="pop_Content_close" title="关闭" id="pop_close_1" onclick="$(\'#window\').remove();$(\'#open\').dialog(\'close\');" href="javascript:;">X</a>';
    html += '</div>';
    html += '</div>';
    html += '<div class="pop_Main" style="position:relative; height:302px; overflow:hidden;">';
    html += '<iframe id="pop_frame_1" frameborder="0" scrolling="no" haslayout="-1" src="http://login.sdo.com/sdo/Login/LoginFrameFC.php?pm=2&appId=200020500&areaId=1&cssId=u17&returnURL='+url+'" style="position:absolute; top:-38px;"></iframe>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    $("body").append(html);
    $('#open').dialog({width:435,height:340,modal:true,title:''}).dialog('open');
    $('.popWindow').hide();
}

/**
 * ================================
 *        建立昵称/收藏漫画等
 * ================================
 */

/* 传递一个元素，返回该元素居中所需的坐标 */
function centerPosition(obj) {
    var docWidth = $(document).width();
    var docHeight = $(document).height();
    var objWidth = $(obj).width();
    var objHeight = $(obj).height();
    var l, t;
    if (objWidth < docWidth) {
        l = (docWidth - objWidth) / 2;
    } else {
        l = 0
    }
    if (objHeight < docHeight) {
        t = (docHeight - objHeight) / 2;
    }
    return {left: l, top: t};
}

function rightHidePosition(obj) {
    var docWidth = $(document).width() - 100;
    var docHeight = $(document).height() - 100;
    var l = docWidth;
    var t = docHeight;
    return {left: l, top: t};
}

function animate(obj, initJson, targetJson, speed, callback) {
    var percent = 0;
    var scaleTotal = targetJson.scale - initJson.scale;
    var rotateTotal = targetJson.rotate - initJson.rotate;
    clearInterval(timer);
    var timer = setInterval(function () {
        percent += 0.025;
        var curScale = initJson.scale + scaleTotal * percent;
        var curRotate = initJson.rotate + rotateTotal * percent;
        if (percent >= 0.98) {
            $(obj).css({
                "transform": "scale(" + targetJson.scale + ") rotate(" + targetJson.rotate + "deg)",
                "-webkit-transform": "scale(" + targetJson.scale + ") rotate(" + targetJson.rotate + "deg)",
                "-moz-transform": "scale(" + targetJson.scale + ") rotate(" + targetJson.rotate + "deg)",
                "-ms-transform": "scale(" + targetJson.scale + ") rotate(" + targetJson.rotate + "deg)",
                "-o-transform": "scale(" + targetJson.scale + ") rotate(" + targetJson.rotate + "deg)"
            });
            clearInterval(timer);
            if (callback) {
                callback();
            }
        } else {
            $(obj).css({
                "transform": "scale(" + curScale + ") rotate(" + curRotate + "deg)",
                "-webkit-transform": "scale(" + curScale + ") rotate(" + curRotate + "deg)",
                "-moz-transform": "scale(" + curScale + ") rotate(" + curRotate + "deg)",
                "-ms-transform": "scale(" + curScale + ") rotate(" + curRotate + "deg)",
                "-o-transform": "scale(" + curScale + ") rotate(" + curRotate + "deg)"
            })
        }
    }, 15)
}
// 显示弹出框
function showPop(obj){
    $(obj).css("visibility","visible");
    animate(obj,{
        scale:0.4,
        rotate:-30
    },{
        scale:1,
        rotate:0
    },15);
    var targetJson = centerPosition(obj);

    $(obj).velocity({
        left:targetJson.left,
        top:targetJson.top
    },{
        duration:600
    })
}
// IE下 显示弹出框
function IEshowPop(obj){
    $(obj).css("visibility","visible");
    var windowHeight = $(window).height();
    var objWidth = obj.width();
    var objHeight = obj.height();
    $(obj).css({
        "left":"50%",
        "top":(windowHeight-objHeight)/2,
        "margin-left":-objWidth/2,
        "display":"none"
    });
    $(obj).fadeIn(300)
}
// 隐藏弹出框
function hidePop(obj){
    var targetJson = rightHidePosition($(".popContent1"));
    setTimeout(function(){

        $(obj).velocity({
            left:targetJson.left,
            top:targetJson.top
        },{
            duration:600,
            complete:function(){
                $(obj).css("visibility","hidden")
            }
        });

    },20)
    animate(obj,{
        scale:1,
        rotate:0
    },{
        scale:0.4,
        rotate:30
    },20)
}
// IE下 隐藏弹出框
function IEfadePop(obj) {
    $(obj).fadeOut(300, function () {
        $(obj).css("visibility", "hidden")
    });
}

$(function() {
    // 关闭弹出框
    $('.popContent .close').click(function() {
        $(this).parent().css("top", $(document).height() + "px");
        $('.mask').hide();
    });
    //初始隐藏弹出框
    $(".popContent").css("top", $(document).height() + "px");
    /* pop2 滚动条 */
    $('.pc2_rightList ul').each(function (index, element) {
        $(this).jScrollPane({showArrows: false, scrollbarWidth: 10});
    });

    //禁止ctrl键
    $(document).keydown(function (e) {
        if (e.ctrlKey && e.keyCode == 65) {
            return false;
        }
    });

    // 昵称
    $(".nickname").click(function () {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
        $(".n_txt").each(function (index, element) {
            $(this).removeClass("current");
        });

    }).blur(function () {
        if (this.value == "") {
            this.value = this.defaultValue;
        } else {
            //验证昵称是否存在
            $.get(_check_nickname_url, {'signup_nickname': this.value}, function (o) {
                if (o.code > 0) {
                    $(".rnb_cannot").hide();
                    $(".rnb_can").html("<em></em>" + o.message).show();
                } else {
                    $(".rnb_can").hide();
                    $(".rnb_cannot").html("<em></em>" + o.message).show();
                    return false;
                }
            }, 'json')
        }
        $(this).removeClass("current");
    });

    $(".reminder_name_box2").hover(function () {
        $(this).addClass("hover");
    }, function () {
        $(this).removeClass("hover")
    });

    var has_num = 0;
    $(".pc2_leftNav li").each(function (index, element) {
        $(this).click(function () {
            var comicType = $(this).attr("comicType");
            var comicText = $(this).attr("comicText");

            showComicByType($(this));

            if (has_num > 3 && $(this).hasClass("isSelected") == false) {
                show_fav_error("最多选择4个分类");
                return false;
            }

            var has_fav_num = getFavComicIds();

            $(this).toggleClass("isSelected");
            var _check_fav_div = "#" + comicType + "_fav_div";

            //判断当前是否选择收藏漫画分类
            if ($(this).hasClass("isSelected")) {
                has_num++;
                $(_check_fav_div + " .pc2_btnBox a").each(function () {
                    $(this).removeClass("cancel").text("已收藏");
                })
                var has_fav_num_add = getFavComicIds();

                $(".p2_s1_list").append("<li comicType=" + comicType + " class='current' onclick='showComicByType(this)'>" + comicText + "</li>");
                $(".p2_s1_list li").each(function () {
                    if ($(this).attr("comicType") != comicType) {
                        $(this).removeClass("current");
                    }
                })
                $(".p2_s1_str span").html(has_fav_num_add);
            } else {
                has_num--;
                $(_check_fav_div + " .pc2_btnBox a").each(function () {
                    $(this).addClass("cancel").text("加收藏");
                })
                var has_fav_num_reduction = getFavComicIds();

                $(".p2_s1_list li").each(function () {
                    if ($(this).attr("comicType") == comicType) {
                        $(this).remove();
                        $(".p2_s1_list li:last-child").addClass("current");
                    }
                })
                $(".p2_s1_str span").html(has_fav_num_reduction);
            }

            if (has_num < 0) {
                $(".pc2_rightList .pc2_rightList_box").eq(0).addClass("current").siblings().removeClass("current");
                $(".pc2_rightList .pc2_rightList_box").eq(0).each(function (index, element) {
                    $(this).find(".pc2_btnBox a").removeClass("cancel").text("已收藏");
                })
                $(".p2_s1_list li").eq(0).addClass("current");
            }
        })
    });
});


/**PHP脚本增加部分**/

//收藏漫画按钮鼠标移上颜色变化
$("#confirm_favorite_comics").mouseover(function() {
    if ($(this).attr("class") == "pc2_go") {
        $(this).attr("style", "opacity:0.70; filter:alpha(opacity=70);");
    }
})
$("#confirm_favorite_comics").mouseout(function() {
    if ($(this).attr("class") == "pc2_go") {
        $(this).attr("style", "opacity:0.90; filter:alpha(opacity=90);");
    }
});

//获取已经增加收藏的漫画总数
function getFavComicIds(){
    var num = 0;
    $(".pc2_leftNav li").each(function(){
        if($(this).hasClass("isSelected")){
            var _check_div = "#"+$(this).attr("comicType")+"_fav_div";
            $(_check_div+" .pc2_btnBox a").each(function(){
                var _a_class = $(this).attr("class");
                if(_a_class == ''){
                    num++;
                }
            })
        }
    });
    //增加推荐收藏漫画
    $("#rec_fav_div .pc2_btnBox a").each(function(){
        var _a_class = $(this).attr("class");
        if(_a_class == ''){
            num++;
        }
    });
    return num;
}

function showComicByType(obj){
    var comicType = $(obj).attr("comicType");
    var _list_div = comicType + "_fav_div";

    $(obj).addClass("current").siblings("li").removeClass("current");
    $("#"+_list_div).addClass("current").siblings("div").removeClass("current");
}

//收藏漫画错误信息展示
function show_fav_error(msg){
    $(".p2_s1_str").css({"color":"#ed0000","position":"relative"}).html(msg);
    $(".p2_s1_str").velocity({
        left:5
    },{
        duration:70,
        loop:2
    })
}

/**用户保存昵称进入下一步**/
$("#confirm_nickname").click(function() {
    submit_user_nickname(this);
});

/**用户不输入昵称进入下一步**/
$("#ignore_nickname").click(function(){
    window.location.href = _cfg_host_base;
});

function submit_user_nickname(btn_obj) {
    var signup_nickname = $("#signup_nickname").val();
    if (signup_nickname == '' || signup_nickname == '快起个萌炫称号') {
        $(".rnb_can").hide();
        $(".rnb_cannot").html("<em></em>请输入正确的昵称!").show();
        return false;
    }
    $(btn_obj).addClass('disable').text('正在登录');
    $(btn_obj).unbind('click');

    $.post(_update_nickname_url, {"signup_nickname": signup_nickname}, function (o) {
        if (o.code > 0) {
            window.location.href = _cfg_host_base;
        } else {
            $(btn_obj).removeClass('disable').text('下一步');
            $(btn_obj).bind('click', function () {
                submit_user_nickname(btn_obj);
            });

            $(".rnb_can").hide();
            $(".rnb_cannot").html("<em></em>" + o.message).show();
            return false;
        }
    }, "json");
}

/**注册成功后显示填写昵称弹框**/
function show_update_nickname(){
    if(window.applicationCache){
        animate($("#register_box"),{
            scale:1,
            rotate:0
        },{
            scale:.4,
            rotate:30
        },15)
        var targetJson = rightHidePosition($("#register_box"));
        $($("#register_box")).velocity({
            right:-500,
            top:targetJson.top
        },{
            duration:800
        })
    }else{
        $("#register_box").fadeOut(300);
    }
    if(window.applicationCache){
        showPop($(".popContent1"));
    }else{
        IEshowPop($(".popContent1"));
    }
}